package xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 注册消息的处理类
 * 方法parseXML :解析消息
 * 方法createDocument :生成消息
 * @author liujh
 *
 */
public class ConnectMsg
{

	/**
	 * 返回结果数组，共三个值：
	 * result[0]:终端ID
	 * result[1]:终端IP
	 * result[2]:终端version
	 * result[3]:终端监听端口号
	 */
	private Object[] result = new Object[3];
	
	
	public static void main(String[] args)
	{
		ConnectMsg rm = new ConnectMsg();
		String ss = rm.createDocument(0L);
		System.out.println(ss);
		Object[] rst = rm.parseXML(ss);
		System.out.println(rst[0]);
		System.out.println(rst[1]);
		System.out.println(rst[2]);
	}
	/**
	 * 解析消息
	 */
	public Object[] parseXML(String xml)
	{
		Document doc=null;
		try
		{
			doc = DocumentHelper.parseText(xml);
		} catch (DocumentException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Element message = doc.getRootElement(); 
		String sessionid = message.elementText("sessionid");
		String ip = message.elementText("ip");
		String version = message.elementText("version");
		//设置返回值数组
		
		result[0]= sessionid;
		result[1]= ip;
		result[2]= version;
		return result;
	}
	/**
	 * 生成消息
	 * @param clientId ：终端id
	 * @param clientIp ：终端ip
	 * @return 返回注册消息
	 */
	public String createDocument(Long clientId)
	{
		String message = "";
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("message");
		Element type = root.addElement("type");
		Element sender = root.addElement("sender");
		Element receiver = root.addElement("receiver");
		Element content = root.addElement("content");
		Element timestamp = root.addElement("timestamp");
		type.addText("Welcome");
		sender.addText("0");
		receiver.addText(clientId.toString());
		content.addText("");
		timestamp.addText("");
		message = document.asXML();
		return message;
	}
}
